package org.example.utils;

import com.alibaba.fastjson2.JSON;
import org.example.factory.messagequeue.UserFactory;
import org.example.model.messagequeue.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangy
 * @description
 * @since 2023/2/8 10:17
 **/
@Component
public class RedisUtils {

    private static final List<String> M_KEY = new ArrayList<>();

    //键数量
    private static final int KEY_NUM = 100;

    static {
        for (int i = 0; i < KEY_NUM; i++) {
            M_KEY.add("user" + (i + 1));
        }
    }

    /**
     * 注入redisTemplate bean
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /*
     * @description 获取多个值
     * @author huangy
     * @since 2023/2/9 11:09
     * @return java.util.List<org.example.model.message-queue.User>
     **/
    public List<User> mGet() {
        List<User> users = new ArrayList<>();
        List<Object> objects = redisTemplate.opsForValue().multiGet(M_KEY);
        assert objects != null;
        for (Object object : objects) {
            String str = object.toString();
            users.add(JSON.parseObject(str, User.class));
        }
        return users;
    }

    /*
     * @description 将用户批量设置到redis中
     * @author huangy
     * @since 2023/2/8 10:53
     * @param users
     * @return boolean
     **/
    public boolean mSet() {
        for (int i = 0; i < M_KEY.size(); i++) {
            redisTemplate.opsForValue().set(M_KEY.get(i), JSON.toJSONString(UserFactory.createUser()));
        }
        return true;
    }


    public void mDel() {
    }

}
